package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gamll.feign.order.OrderFeignClient;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;

/**
 * @author lhh
 * @ClassName PayServiceImpl
 * @date 2022 2022/12/25
 */
@Service
public class PayServiceImpl implements PayService {

    @Resource
    OrderFeignClient orderFeignClient;

    @Resource
    AlipayClient alipayClient;

    @Resource
    AlipayProperties alipayProperties;

    @Override
    public String generatePayPage(Long orderId, Long userId) throws AlipayApiException {
        //创建一个请求
        AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();
        payRequest.setReturnUrl(alipayProperties.getReturnUrl());
        payRequest.setNotifyUrl(alipayProperties.getNotifyUrl());

        //4、准备待支付的订单数据
        //远程调用订单服务，获取订单的基本数据，基于此数据构造一个支付页
        OrderInfo orderInfo = orderFeignClient.getOrderInfoById(orderId).getData();

        //订单号
        String outTradeNo = orderInfo.getOutTradeNo();
        //付款金额
        BigDecimal totalAmount = orderInfo.getTotalAmount();

        //订单名称
        String orderName = "尚品汇-订单-"+outTradeNo;
        //商品描述
        String tradeBody = orderInfo.getTradeBody();

        HashMap<String, Object> bizContent = new HashMap<>();
        bizContent.put("out_trade_no",outTradeNo);
        bizContent.put("total_amount",totalAmount);
        bizContent.put("subject",orderName);
        bizContent.put("body",tradeBody);
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");

        //支付宝自动关单功能
        String date = DateUtil.formatDate(orderInfo.getExpireTime(), "yyyy-MM-dd HH:mm:ss");
        bizContent.put("time_expire",date);
        payRequest.setBizContent(JSON.toJSONString(bizContent));
        //生成支付页面
        String page = alipayClient.pageExecute(payRequest).getBody();
        return page;
    }
}
